<?php

namespace App\Jobs\System;
// 加载采集环境

use App\Wen\Utils\StrUtils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class StrReplaceStrJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $old_str = '';
    protected $new_str = '';
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($old_str, $new_str)
    {
        $this->old_str = $old_str;
        $this->new_str = $new_str;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $old_str = $this->old_str;
        $new_str = $this->new_str;

        if(_empty_($old_str)){
            return;
        }
        if(_empty_($new_str)){
            $new_str = '';
        }

        DB::beginTransaction();
        try {
            // todo:
            $tables = DB::select('SHOW TABLES');
            $tableNames = array_map('current', $tables);
            if($tableNames){
                foreach ($tableNames as $table_name){
                    if(StrUtils::startsWith($table_name, 'admin_')){
                        continue;
                    }
                    if(!StrUtils::startsWith($table_name, 'wx_') && !StrUtils::startsWith($table_name, 'mini_')){
                        continue;
                    }
                    $table_info_columns = DB::select( DB::raw('SHOW COLUMNS FROM '.$table_name));
                    foreach($table_info_columns as $column){
                        if(in_array($column->Field, ['id', 'deleted_at', 'created_at', 'updated_at']) || StrUtils::endsWith($column->Field, '_id')){
                            continue;
                        }
                        if(strpos($column->Type, 'int') !== false){
                            continue;
                        }
                        if(in_array($column->Field, ['desc', 'right', 'condition', 'key'])){
                            continue;
                        }
                        DB::select("UPDATE ".$table_name." SET ".$column->Field." = REPLACE(".$column->Field.", '".$old_str."', '".$new_str."') WHERE ".$column->Field." LIKE '%".$old_str."%'");
                    }
                }
            }
            Cache::tags('st')->flush();

            DB::commit();
            return;
        } catch (\Exception $e) {
            DB::rollBack();
            _logger_(__file__, __line__, $e->getMessage());
            return;
        }
    }
}
